package com.vim.modules.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vim.common.annotation.SysLogRecord;
import com.vim.common.annotation.SysLoginLogRecord;
import com.vim.common.base.Constants;
import com.vim.common.model.response.Response;
import com.vim.common.model.response.RestfulResponse;
import com.vim.common.model.response.TableListResponse;
import com.vim.common.utils.IdGen;
import com.vim.common.utils.ValidateUtils;
import com.vim.common.utils.VerifyCodeUtils;
import com.vim.modules.web.model.SysUser;
import com.vim.modules.web.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    /**
     * 所有用户
     */
    @RequestMapping("/list")
    public TableListResponse list(SysUser sysUser, @RequestParam(value = "page") Integer page, @RequestParam(value = "limit") Integer limit){
        ValidateUtils.checkNotZero(page);
        ValidateUtils.checkNotZero(limit);
        PageHelper.startPage(page,limit);
        List<SysUser> list = sysUserService.findList(sysUser);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return new TableListResponse(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 编辑用户
     */
    @SysLogRecord
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestfulResponse edit(SysUser sysUser){
        if(StringUtils.isNoneBlank(sysUser.getUserId())){
            sysUserService.update(sysUser);
        }else{
            ValidateUtils.checkNotBlank(sysUser.getNickname());
            ValidateUtils.checkNotBlank(sysUser.getLoginAccount());
            SysUser exist = sysUserService.findLoginAccount(sysUser.getLoginAccount());
            if(null != exist){
                return new RestfulResponse(RestfulResponse.DEFAULT_ERROR, "用户已存在");
            }else{
                sysUserService.save(sysUser);
            }
        }
        return new RestfulResponse(Response.OK);
    }

    /**
     * 用户详情
     */
    @RequestMapping("/detail")
    public RestfulResponse detail(@RequestParam(value = "id") String id){
        ValidateUtils.checkNotBlank(id);
        return new RestfulResponse(sysUserService.find(id));
    }

    /**
     * 删除用户
     */
    @SysLogRecord
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public RestfulResponse del(@RequestParam(value = "id") String id){
        ValidateUtils.checkNotBlank(id);
        if("-1".equals(id)){
            return new RestfulResponse(500, "管理员不可删除");
        }else{
            sysUserService.deleteUser(id);
            return new RestfulResponse(Response.OK);
        }
    }

    /**
     * 验证码
     */
    @RequestMapping(value = "/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        HttpSession session = request.getSession(true);
        //删除以前的
        session.removeAttribute(Constants.VERIFY_CPDE);
        session.setAttribute(Constants.VERIFY_CPDE, verifyCode.toLowerCase());
        //生成图片
        int w = 130, h = 38;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }

    /**
     * 登录
     */
    @SysLoginLogRecord
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public RestfulResponse login(@RequestParam(value = "loginAccount") String loginAccount,
                                 @RequestParam(value = "loginPassword") String loginPassword,
                                 @RequestParam(value = "verifyCode") String verifyCode,
                                 HttpServletRequest request){
        ValidateUtils.checkNotBlank(loginAccount);
        ValidateUtils.checkNotBlank(loginPassword);
        ValidateUtils.checkNotBlank(verifyCode);

        HttpSession session = request.getSession();
        Object code = session.getAttribute(Constants.VERIFY_CPDE);
        if(null == code || !code.toString().equals(verifyCode)){
//            return new RestfulResponse(RestfulResponse.VERIFY_CODE_ERROR, "验证码错误");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(loginAccount);
        token.setPassword(loginPassword.toCharArray());
        subject.login(token);

        SysUser loginUser = (SysUser)subject.getPrincipal();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(loginUser.getUserId());
        sysUser.setLoginAccount(loginUser.getLoginAccount());
        sysUser.setNickname(loginUser.getNickname());
        sysUser.setUserAvatar(loginUser.getUserAvatar());
        return new RestfulResponse(sysUser);
    }

    /**
     * 登出
     */
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    public RestfulResponse loginOut(){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            subject.logout();
        }
        return new RestfulResponse(Response.OK);
    }

    /**
     * 修改密码
     */
    @SysLogRecord
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public RestfulResponse changePassword(@RequestParam(value = "password") String password,
                                          @RequestParam(value = "repeatPassword") String repeatPassword){
        ValidateUtils.checkNotBlank(password);
        ValidateUtils.checkNotBlank(repeatPassword);
        if(!password.equals(repeatPassword)){
            return new RestfulResponse(RestfulResponse.VERIFY_CODE_ERROR, "两次密码不一致");
        }

        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            return new RestfulResponse(RestfulResponse.VERIFY_CODE_ERROR, "用户没有登录");
        }

        SysUser sysUser = (SysUser) subject.getPrincipal();
        sysUser.setLoginPassword(IdGen.password(sysUser.getLoginAccount(), password));
        sysUserService.update(sysUser);
        subject.logout();
        return new RestfulResponse(Response.OK);
    }

    /**
     * 上传头像
     */
    @RequestMapping(value = "/editAvatar", method = RequestMethod.POST)
    public RestfulResponse editAvatar(MultipartFile userAvatar){
        return new RestfulResponse(Response.OK);
    }
}

